# Copyright (c) Quectel Wireless Solution, Co., Ltd.All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

# Copyright (c) Quectel Wireless Solution, Co., Ltd.All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import _thread
import checkNet
import modem
from queue import Queue
from usr.serial import Serial
from usr.mqttIot import MqttIot
from usr.logging import getLogger

logger = getLogger(__name__)


class DTU(object):

    def __init__(self, config):
        self.queue = Queue()  # DTU应用与MQTT
        self.serial = Serial(**config.get('uart_config'))

        mqtt_config = config.get('aiot')
        self.cloud = MqttIot(
            "TYWL" + modem.getDevImei(),
            mqtt_config['server'],
            port=mqtt_config['port'],
            user="TYWL" + modem.getDevImei(),
            password=mqtt_config['password'],
            keepalive=mqtt_config['keepalive'],
            clean_session=mqtt_config['clean_session'],
            qos=mqtt_config['qos'],
            subscribe_topic=mqtt_config['subscribe'],
            publish_topic=mqtt_config['publish'],
            queue=self.queue,
            error_trans=True
        )

    def run(self):
        # 初始化云对象
        self.cloud.init()
        # 启动上行数据处理线程
        self.up_transaction()
        # 启动下行数据处理线程
        self.down_transaction()

    def down_transaction(self):
        logger.info('start down transaction worker thread {}.'.format(_thread.get_ident()))
        _thread.start_new_thread(self.down_transaction_handler, ())

    def down_transaction_handler(self):
        while True:
            topic, data = self.cloud.recv()
            logger.info('down transfer msg: {}'.format(data))
            self.serial.write(data)

    def up_transaction(self):
        logger.info('start up transaction worker thread {}.'.format(_thread.get_ident()))
        _thread.start_new_thread(self.up_transaction_handler, ())

    def up_transaction_handler(self):
        while True:
            data = self.serial.read(1024, timeout=100)
            stage, state = checkNet.waitNetworkReady(30)
            if data and stage == 3 and state == 1:
                logger.info('up transfer msg: {}'.format(data))
                self.cloud.send(data)
            elif data:
                logger.info('pub fail, net not ready!')
